package com.zhijian.controller.admin;

import com.zhijian.entity.Note;
import com.zhijian.entity.PageBean;
import com.zhijian.entity.R;
import com.zhijian.service.INoteService;
import com.zhijian.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/note")
public class AdminNoteController {

    @Autowired
    private INoteService noteService;

    @Value("${noteImagesFilePath}")
    private String noteImagesFilePath;

    /**
     * 根据条件分页查询笔记
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean) {
        Map<String,Object> map = new HashMap<>();
        map.put("query", pageBean.getQuery().trim());
        map.put("pageNum", pageBean.getPageNum());
        map.put("pageSize", pageBean.getPageSize());
        
        List<Note> list = noteService.list(map);
        Long total = noteService.getTotal(map);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("noteList", list);
        resultMap.put("total", total);
        return R.ok(resultMap);
    }

    /**
     * 添加或修改笔记
     */
    @PostMapping("/save")
    public R save(@RequestBody Note note) {
        if(note.getId() == null || note.getId() == -1) {
            noteService.add(note);
        } else {
            noteService.update(note);
        }
        return R.ok();
    }

    /**
     * 删除笔记
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id) {
        noteService.removeById(id);
        return R.ok();
    }

    /**
     * 上传笔记封面图片
     */
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file) throws Exception {
        Map<String,Object> map = new HashMap<>();
        if(!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = DateUtil.getCurrentDateStr() + suffixName;

            File uploadDir = new File(noteImagesFilePath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("Directory created: " + created);
            }

            System.out.println("Upload directory path: " + uploadDir.getAbsolutePath());
            System.out.println("Upload directory exists: " + uploadDir.exists());
            System.out.println("Upload directory can read: " + uploadDir.canRead());
            System.out.println("Upload directory can write: " + uploadDir.canWrite());
            System.out.println("New file name: " + newFileName);

            File dest = new File(uploadDir, newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
            
            System.out.println("Uploaded file path: " + dest.getAbsolutePath());
            System.out.println("Uploaded file exists: " + dest.exists());
            System.out.println("Uploaded file can read: " + dest.canRead());
            
            String imageUrl = "/image/note/" + newFileName;
            System.out.println("Image URL: " + imageUrl);

            // 尝试直接访问文件
            try {
                byte[] content = FileUtils.readFileToByteArray(dest);
                System.out.println("File content length: " + content.length);
            } catch (Exception e) {
                System.out.println("Error reading file: " + e.getMessage());
            }

            map.put("code", 0);
            map.put("msg", "上传成功");
            Map<String,Object> data = new HashMap<>();
            data.put("title", newFileName);
            data.put("src", imageUrl);
            map.put("data", data);
        }
        return map;
    }

    /**
     * 根据id查询笔记详情
     */
    @GetMapping("/{id}")
    public R detail(@PathVariable(value = "id") Integer id) {
        Note note = noteService.getById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("note", note);
        return R.ok(map);
    }
} 